package com.example.a02back.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.a02back.common.APIResponse;
import com.example.a02back.dto.MyDone;
import com.example.a02back.dto.UserCard;
import com.example.a02back.entity.Card;
import com.example.a02back.entity.Trade;
import com.example.a02back.entity.User;
import com.example.a02back.mapper.UserMapper;
import com.example.a02back.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author SimpChaos
 * @since 2022-07-02
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.secret}")
    private String secret;

    @Resource
    private  AuthServicelmpl auth;

    @Resource
    private CardServiceImpl cardService;


/**
 * @Description:
 * @Author: SimpChaos
 * @Date: 2022/7/15 21:02
 * @Param: [code]
 * @Return: java.lang.String
 */
    public String authorize(String code){

        return auth.getSession(code);
    }



/**
 * @Description:
 * @Author: SimpChaos
 * @Date: 2022/7/15 21:02
 * @Param: [sessionId, encryptedData, iv]
 * @Return: com.example.a02back.common.APIResponse<?>
 */
    public APIResponse<?> login(String sessionId, String encryptedData, String iv)  {

        try{

            //由sessionId取到redis里的用户信息
            JSONObject jsonObject = auth.wxDecrypt(sessionId,encryptedData,iv);
            String wxRes = auth.getUserInfo(sessionId, encryptedData, iv,jsonObject);
            //用户信息：{"openId":"o20","nickName":"juana","gender":2,"language":"zh_CN","city":"Changsha","province":"Hunan","country":"China","avatarUrl":"头像链接","watermark":{"timestamp":dsfs,"appid":"应用id"}}
            log.info("用户信息："+wxRes);
            User user = JSON.parseObject(wxRes,User.class);
            System.out.print(user);

            String op = auth.getOpenid(jsonObject);

            //检测是否已有信息
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getOid,op);
            User user2 = this.getOne(wrapper);
            log.info("在这里哦");
            System.out.print(!(user2 == null));

            if(!(user2 == null))  {
                return APIResponse.success("registed user",auth.getToken(op));
            }

            user.setOid(op);
            user.setUid(RandomUtil.randomNumbers(20));
            //mybatis整个活儿
            this.save(user);
            System.out.print(user);

            //生成token
            return APIResponse.success("SUCCESS",auth.getToken(user.getOid()));

        }catch (Exception e) {
            e.printStackTrace();
        }

        return APIResponse.fail("login方法出错");
    }


    /**
     * @Description:
     * @Author: SimpChaos
     * @Date: 2022/7/20 19:43
     * @Param: [code, nickname, touxiang]
     * @Return: com.example.a02back.common.APIResponse<?>
     */

    public APIResponse<?> Login(String code,String nickname,String touxiang){
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        String replaceUrl = url.replace("{0}", appid).replace("{1}", secret).replace("{2}", code);
        String res = HttpUtil.get(replaceUrl);
        JSONObject jsonObject = JSON.parseObject(res);
        String openid = (String) jsonObject.get("openid");
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getOid,openid);
        if(!(this.getOne(wrapper) == null))  return APIResponse.success("REGISTED USER",auth.getToken(openid));
        User user = new User();
        user.setUid(RandomUtil.randomNumbers(20));
        user.setNickname(nickname);
        user.setAvatarUrl(touxiang);
        user.setOid(openid);
        user.setGender("0");
        this.save(user);
        return APIResponse.success("SUCCESSS",auth.getToken(openid));
    }




    /**
     * @Description:
     * @Author: SimpChaos
     * @Date: 2022/7/15 21:02
     * @Param: [uid, department, position]
     * @Return: java.lang.String
     */
    public String choose(String cardid){
        LambdaQueryWrapper<Card> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Card::getChose,"1");
        Card c = cardService.getOne(wrapper);
        c.setChose("0");
        cardService.updateById(c);

        Card card =cardService.getById(cardid);
        card.setChose("1");
        cardService.updateById(card);

        User user = this.getById(card.getUid());
        user.setDepartment(card.getOrgnizinfo());
        user.setPosition(card.getAuthinfo());
        String rows = String.valueOf(this.updateById(user));
        return "success";
    }


    /**
     * @Description:
     * @Author: SimpChaos
     * @Date: 2022/7/15 21:02
     * @Param: [uid]
     * @Return: com.example.a02back.dto.UserCard
     */
    public UserCard getUserCard(String uid){
        User user = this.getById(uid);
        UserCard card = new UserCard();
        BeanUtil.copyProperties(user,card);
        return card;
    }



    /**
     * @Description:
     * @Author: SimpChaos
     * @Date: 2022/7/15 21:02
     * @Param:
     * @Return:

    public String favoriteItem(String uid,String sid){
        S
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getUid,uid).set(User::getFavoriteItem,)
        this.update()




    } */

}
